package org.base.sys.service.impl;

import lombok.AllArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.base.sys.pojo.SysUserRole;
import org.base.sys.dao.SysUserRoleMapper;
import org.base.sys.service.SysUserRoleService;
import org.base.common.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.base.sys.query.SysUserRoleQuery;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户和角色关联 服务实现类
 * </p>
 *
 * @author AutoGenerator
 * @since 2020-05-27
 */
@Service
@Slf4j
@AllArgsConstructor
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole, SysUserRoleQuery>implements SysUserRoleService {

    @Override
    public void updateUserRole(Long userId, List<Long> roles) {
        lambdaUpdate().eq(SysUserRole::getUserId, userId)
                .remove();
        if (CollectionUtils.isNotEmpty(roles)) {
            List<SysUserRole> userRoles = new ArrayList<>(roles.size());
            SysUserRole userRole;
            for (Long roleId : roles) {
                userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                userRoles.add(userRole);
            }
            saveBatch(userRoles);
        }
    }

    @Override
    public List<Long> getUserRoleIds(Long userId) {
        return lambdaQuery().eq(SysUserRole::getUserId, userId)
                .list().stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
    }

}
